package com.franklin.ideaplugin.api.utils.psi;

import cn.hutool.core.collection.CollectionUtil;
import com.intellij.psi.PsiCodeBlock;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiReturnStatement;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Ye Junhui
 * @since 2024/3/7
 */
public class PsiCodeBlockUtils {

    /**
     * 寻找代码块返回对象
     * @param psiCodeBlock
     * @return
     */
    @NotNull
    public static List<PsiExpression> findCodeBlockReturnExpression(PsiCodeBlock psiCodeBlock){
        if (Objects.isNull(psiCodeBlock)){
            return null;
        }
        //寻找返回语句
        List<PsiReturnStatement> psiReturnStatementList = PsiTreeUtil.getChildrenOfTypeAsList(psiCodeBlock, PsiReturnStatement.class);
        return psiReturnStatementList.stream()
                .map(PsiReturnStatement::getReturnValue)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
